package cn.lzh.controller;

import cn.lzh.entity.Cart;
import cn.lzh.entity.CartBook;
import cn.lzh.entity.Order;
import cn.lzh.entity.Orditem;
import cn.lzh.service.CartService;
import cn.lzh.service.OrderService;
import cn.lzh.tool.RespJson;
import cn.lzh.tool.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/fore/cart")
public class CartController {
    @Autowired
     CartService cartService;
    @Autowired
    OrderService orderService;

    //查询
    @RequestMapping("/findAll")
    public Map<String, Object> findAllCartByUid() {
        int uid = Token.getUid();//获取UID
        if (uid < 0) {
            return RespJson.pack(401, "未登录", null);
        } else {
            List<CartBook> lst = this.cartService.findByUid(uid);
            return RespJson.pack(200, "", lst);
        }
    }
   //添加购物车
    @RequestMapping("/addCart/{bookid}")
    public Map<String, Object> goCart(Cart cart , @PathVariable("bookid") int bookid ) {
        System.out.println("id=" + bookid);
        int uid = Token.getUid();//获取UID
        if (uid < 0) {
            return RespJson.pack(401, "你未登录， 请登录 .....", 0);
        } else {
            cart.setBookid(bookid);
            cart.setUid(uid);
            cart.setNum(1);
            cartService.add(cart);
            return RespJson.pack(200, "加入购物车成功 ...", null);
        }
    }




    @RequestMapping("/addCart2Order")
    @ResponseBody
    public Map<String, Object> postCart(@RequestBody List<Orditem> items) {
        int uid = Token.getUid();
        if (uid < 0) {
            return RespJson.pack(401, "未登录或登录超时", null);
        } else {
            System.err.println(items);
            Order ord = new Order();
            ord.setUid(uid);
            System.err.println("/addCart2Order 参数: order=" + ord + "\r\n items=" + items);

            try {
                this.orderService.addOrdItem(ord, items);
            } catch (Exception a) {
                a.printStackTrace();
                System.err.println(a);
                return RespJson.pack(500, "成功接收到数据, 但更新订单失败 ....", null);
            }
            return RespJson.pack(200, "成功接收到数据, 并产生订单 ....", ord);
        }
    }
}
